# Copyright (c) 2006 Erik Hatcher, Thiago Jackiw
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

require 'active_record'
require 'rexml/document'
require 'net/http'
require 'yaml'

require File.dirname(__FILE__) + '/solr'
require File.dirname(__FILE__) + '/acts_methods'
require File.dirname(__FILE__) + '/class_methods'
require File.dirname(__FILE__) + '/instance_methods'
require File.dirname(__FILE__) + '/common_methods'
require File.dirname(__FILE__) + '/deprecation'
require File.dirname(__FILE__) + '/search_results'
require File.dirname(__FILE__) + '/query_builder'

module ActsAsSolr
  mattr_accessor :config

  def self.load_config
    config = YAML.load(ERB.new(File.read(RAILS_ROOT+'/config/solr.yml')).result)
    ActsAsSolr.config = config
  end

  SPECIAL_CHARACTERS = %w(+ - && || ! ( ) { } [ ] ^ " ~ * ? : \\)
  def self.escape_value(valu)
    valu = valu.gsub('\\','')
    SPECIAL_CHARACTERS.each do |str|
      valu = valu.gsub(str, "\\#{str}")
    end
    valu
  end

  def self.without_async_threads(&block)
    Thread.current["no_solr_threads"] = true
    begin
      yield
    ensure
      Thread.current["no_solr_threads"] = nil
    end
  end

  def self.without_autocommit(&block)
    Thread.current["no_solr_commit"] = true
    begin
      yield
    ensure
      Thread.current["no_solr_commit"] = nil
    end
  end

  class Post
    def self.execute(request, commit_after = false)
      begin
        config = ActsAsSolr.config
        write_url = config[RAILS_ENV]['write_url'] || config[RAILS_ENV]['url']
        read_url = config[RAILS_ENV]['read_url'] || config[RAILS_ENV]['url']
        if request.is_a?(Solr::Request::Standard)
          url = read_url
          backup_url = write_url
          threading = false
        else
          url = write_url
          backup_url = nil
          threading = true
        end

        if !threading || Thread.current["no_solr_threads"]
          connection = Solr::Connection.new(url, backup_url)
          result = connection.send(request)
          connection.send(Solr::Request::Commit.new) if commit_after
          return result
        else
          return Thread.new {
            connection = Solr::Connection.new(url, backup_url)
            connection.send(request)
            connection.send(Solr::Request::Commit.new) if commit_after
          }
        end
      rescue
        raise "Couldn't connect to the Solr server at #{url}. #{$!}"
        false
      end
    end
  end

end

# reopen ActiveRecord and include the acts_as_solr method
ActiveRecord::Base.extend ActsAsSolr::ActsMethods